package top.riske.animalhazardassessment.common.filter;

import cn.hutool.jwt.JWTException;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import top.riske.animalhazardassessment.common.DTO.JwtDto;
import top.riske.animalhazardassessment.common.http.exception.AuthorizationExpiredException;
import top.riske.animalhazardassessment.common.http.response.Result;
import top.riske.animalhazardassessment.common.utils.JWTUtils;
import top.riske.animalhazardassessment.common.utils.RequestUtils;
import top.riske.animalhazardassessment.common.utils.ResponseUtils;

import java.io.IOException;

/**
 * 身份信息提取过滤器
 * 从请求头authorization中提取token，并解析出用户身份信息，保存到请求头中
 * 可以在请求头的JwtDto字段中获取到用户身份信息
 * created by vital on 2025/3/2 下午1:10
 */
@Slf4j
public class AuthorizationFilter implements Filter {

    /**
     * 请求头中保存token的key
     */
    public static final String AUTHORIZATION_HEADER = "authorization";
    /**
     * 请求头中保存身份信息的key
     */
    public static final String AUTHORIZATION_DATA_HEADER = "JwtDto";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("AuthorizationFilter执行");
        // 判断是否是http请求
        if(!(servletRequest instanceof HttpServletRequest)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 强制转换为http请求
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        // 从请求头中提取token
        String authorization = httpRequest.getHeader(AUTHORIZATION_HEADER);

        // 判断token是否存在
        if(authorization == null || authorization.isEmpty()){
            // 返回错误信息，token不存在
            log.warn("token不存在，完整请求头：{}",RequestUtils.getAllHeaders(httpRequest));
            Result<Object> result = Result.fail("token不存在", null);
            ResponseUtils.setErrorResponse(httpRequest, httpResponse, result);
            return;
        }

        // 解析token
        try {
            JwtDto jwtDto = JWTUtils.parseJwt(authorization);
            // 将解析出的身份信息保存到请求头中
            httpRequest.setAttribute(AUTHORIZATION_DATA_HEADER, jwtDto);
        } catch (AuthorizationExpiredException e) {
            // 返回错误信息，token过期
            Result<Object> result = Result.fail("token已过期", null);
            ResponseUtils.setErrorResponse(httpRequest, httpResponse, result);
            return;
        } catch (JWTException e){
            // 返回错误信息，token错误
            Result<Object> result = Result.fail("token无效", null);
            ResponseUtils.setErrorResponse(httpRequest, httpResponse, result);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("AuthorizationFilter初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        log.info("AuthorizationFilter销毁");
        Filter.super.destroy();
    }
}
